package com.yjht.online.generate;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.yjht.online.arg.ArgParam;
import com.yjht.online.generate.model.person.SysRole;
import com.yjht.online.util.OnLineFileUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ConfigBootstrap {
    final static Logger logger = LoggerFactory.getLogger(ConfigBootstrap.class);

    public static void config(ArgParam argParam){
        //快贷
        List<SysRole> sysKdRoles = loadRoleConfig("config/kdRole.xml");
        GlobalContext.setSysRoles(sysKdRoles);
        //微营销
        List<SysRole> sysWyxRoles = loadRoleConfig("config/wyxRole.xml");
        GlobalContext.setGetWyxSysRoles(sysWyxRoles);
    }

    private static List<SysRole> loadRoleConfig(String configPath) {

        InputStream inputStream = OnLineFileUtil.getInputStream(configPath);
        if (inputStream == null) {
            logger.error("角色对照配置文件缺失");
            return null;
        }

        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error("xml读取失败"+e.getMessage());
        }
        Element root = document.getRootElement();
        List<Element> childElements = root.elements();

        List<SysRole> sysRoles = new ArrayList<>();
        for (Element child : childElements) {
            SysRole sysRole = new SysRole();
            if(child.element("roleId")==null){
                continue;
            }
            if(child.element("roleName")==null){
                continue;
            }
            String roleId = child.element("roleId").getStringValue();
            String roleName = child.element("roleName").getStringValue();
            sysRole.setRoleId(roleId);
            sysRole.setRoleName(roleName);
            sysRoles.add(sysRole);
        }
        sysRoles = sysRoles.stream().filter(f-> StrUtil.isNotBlank(f.getRoleId())
                && StrUtil.isNotBlank(f.getRoleName())).collect(Collectors.toList());



        return sysRoles;
    }
}
